package com.uroad.liaoningpos.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.uroad.liaoningpos.common.CurrApplication;
import com.uroad.liaoningpos.common.SPContants;
import com.uroad.liaoningpos.model.TransData;
import com.uroad.liaoningpos.util.SPUtils;
import com.uroad.liaoningpos.webService.PosWS;
import com.uroad.lib.data.Constant;
import com.uroad.lib.http.OkHttpUtils;
import com.uroad.lib.http.builder.PostFormBuilder;
import com.uroad.lib.http.callback.StringCallback;
import com.uroad.lib.util.log.LogUtil;
import com.uroad.lib.util.net.NetWorkUtil;
import com.uroad.lib.widget.dialog.DialogHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * @创建者 wlw
 * @创建时间 2019/4/11 14:26
 * @描述
 */
public class UploadService extends Service {
    private List<TransData> datas;
    private Handler         handler = new Handler();
    private long            uploaTime = 5 * 60 * 1000;
    private TransData       transData;
    private String posimei = "";
    private String beonduty = "";
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
//        posimei = (String) SPUtils.get(this, SPContants.SP_IMEI, "");
//        beonduty = (String) SPUtils.get(this, SPContants.SP_BEONDUTY, "");
//        getPayResult();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        posimei = (String) SPUtils.get(this, SPContants.SP_IMEI, "");
        beonduty = (String) SPUtils.get(this, SPContants.SP_BEONDUTY, "");
        getPayResult();
        return super.onStartCommand(intent, flags, startId);
    }

    private void getPayResult() {
        datas = CurrApplication.daoUtils.getAll(TransData.class);
        if (datas != null && datas.size() > 0) {
            //上传
            transData = datas.get(0);
            uploadData();
        }
        handler.postDelayed(uploadRunnable, uploaTime);
    }

    private void uploadData() {

        if(!TextUtils.isEmpty(transData.getAmount())){//消费记录上传
            doRequest(PosWS.pay, PosWS.payParams(transData.getTransAmount(), transData.getMerchantNo(),
                    transData.getMerchantName(), transData.getTerminalNo(),
                    transData.getBatchNo(), transData.getTraceNo(),
                    transData.getRefNo(), transData.getTransChnName(),
                    transData.getCardIssuerCode(), transData.getCardIssuerId(),
                    transData.getCardAcquirerCode(), transData.getCardAcquirerId(),
                    transData.getDate(), transData.getTime(), transData.getMemInfo(),
                    transData.getCardNo(), transData.getPayType(), transData.getOperNo(),
                    posimei,beonduty,transData.getPayVoucherCode(),transData.getInsertid(),transData.getOrderno()), PosWS.pay);
        }else{//撤销记录上传
            doRequest(PosWS.payrevoke, PosWS.payrevokeParams(transData.getVoucherNo(),transData.getTraceNo(),
                transData.getMerchantNo(),transData.getTerminalNo()), PosWS.payrevoke);
        }

    }

    private Runnable uploadRunnable = new Runnable() {
        @Override
        public void run() {
            getPayResult();
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (handler!=null) {
            handler.removeCallbacksAndMessages(null);
        }
    }


    private void OnHttpTaskComplete(String result, String id) {
        try {
            DialogHelper.endLoading();
            JSONObject jsonObject = new JSONObject(result);
            String status = jsonObject.getString("status");
            if ("00".equalsIgnoreCase(status)) {
                CurrApplication.daoUtils.delete(transData);
                if (handler!=null) {
                    handler.removeCallbacksAndMessages(null);
                }
                getPayResult();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void OnHttpFailure(String id) {

    }

    private void OnHttpNetWork(String id) {

    }

    /**
     * 网络请求
     *
     * @param methodUrl url方法名eg."/sys/getFileVer"
     * @param params    请求参数
     * @param id
     */
    public void doRequest(String methodUrl, HashMap<String, Object> params, String id) {
        doPost(Constant.BASE_URL + methodUrl, params, id);
    }

    public void doPost(String url, HashMap<String, Object> params, String id) {
        if (!NetWorkUtil.checkNet(this)) {
            OnHttpNetWork(id);
            return;
        }
        PostFormBuilder postFormBuilder = OkHttpUtils.post();
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                postFormBuilder.addParams(entry.getKey(), entry.getValue() + "");
            }
        }
        postFormBuilder.url(url)
                .id(id)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, String id) {
                        OnHttpFailure(id);
                    }

                    @Override
                    public void onResponse(String response, String id) {
                        try {
                            OnHttpTaskComplete(response, id);
                        } catch (Exception e) {
                            OnHttpFailure(id);
                        }
                    }
                });
    }
}

